package models

import (
	"sync"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type DBConfigHolder struct {
	Gp               *ParameterConfigs
	FlowerAddConfigs map[int]*FloweraddConfigs
}

type DbWrapper struct {
	DbInstance *gorm.DB
	DbConfigs  *DBConfigHolder
}

func NewDb() *DbWrapper {
	obj := new(DbWrapper)

	return obj
}

var instance *DbWrapper
var once sync.Once

func GetInstance() *DbWrapper {
	once.Do(func() {
		instance = NewDb()
	})
	return instance
}

func init() {

}

func (dbw *DbWrapper) Connect(dsn string, poolIdle, poolMax int) *gorm.DB {
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}
	_innerdb, err2 := db.DB()
	if err2 != nil {
		panic(err2)
	}
	_innerdb.SetMaxIdleConns(poolIdle)
	_innerdb.SetMaxOpenConns(poolMax)
	_innerdb.SetConnMaxLifetime(time.Hour)

	dbw.DbInstance = db
	return db
}

func (dbw *DbWrapper) LoadCommonConfigToMemory() {
	u1 := new(ParameterConfigs)
	dbw.DbInstance.First(&u1)
	dbw.DbConfigs = new(DBConfigHolder)
	dbw.DbConfigs.Gp = u1

	var floweraddconfigs []*FloweraddConfigs
	dbw.DbInstance.Find(&floweraddconfigs)
	dbw.DbConfigs.FlowerAddConfigs = make(map[int]*FloweraddConfigs)
	for i := 0; i < len(floweraddconfigs); i++ {
		dbw.DbConfigs.FlowerAddConfigs[floweraddconfigs[i].Level] = floweraddconfigs[i]
	}
	// dbw.DbConfigs.FlowerAddConfigs = floweraddconfigs
}

func (db *DbWrapper) DoOne(username string) *User {
	u1 := new(User)
	db.DbInstance.Model(u1).First(&u1)
	return u1
}
